﻿using SoundEngine3.AudioProcessing.Generators;
using System;

namespace DefaultDspPluginsLib.Depricated
{
    class Effect_SideChaining
    {
        private EnvelopeManager2 mSideChaining;
        private LeapCurveEnvelope up;
        private LinearEnvelope distance;
        private LeapCurveEnvelope down;
        private double mVolyme;
        private double mFallback;
        private double mFallbackCurve;
        private double mFallbackDistance;
        private double chainigPosition;
        private double mFallbackDistanceCalc;

        public EnvelopeManager2 EnvelopeManager { get { return mSideChaining; } }

        public Effect_SideChaining()
        {
            mSideChaining = new EnvelopeManager2();
            up = new LeapCurveEnvelope();
            mSideChaining.Add(up);
            distance = new LinearEnvelope();
            mSideChaining.Add(distance);
            down = new LeapCurveEnvelope();
            mSideChaining.Add(down);
        }

        public void SetVolyme(double value)
        {
            up.Y2 = 1.0;
            up.Y1 = 1 - value;
            distance.Y1 = 1.0;
            distance.Y2 = 1.0;
            down.Y2 = 1 - value;
            down.Y1 = 1.0;
        }

        public void SetFallbackCurve(double value)
        {
            up.Leap = value;
            down.Leap = value;
        }

        public void SetFallback(double value, double beatSamples)
        {
            double fallbackSamples = beatSamples * value;
            double x2 = beatSamples - fallbackSamples;

            up.X2 = Math.Max(0, x2 - mFallbackDistanceCalc);

            distance.X1 = up.X2;
            distance.X2 = x2;

            down.X1 = x2;
            down.X2 = beatSamples;
        }

        public void SetFallbackDistance(double value, double beatSamples)
        {
            mFallbackDistanceCalc = value * beatSamples;

            SetFallback(mFallback, beatSamples);
        }

        public void Process(double chainigPosition, double[] sound_left, double[] sound_right, double[] sound_left_out, double[] sound_right_out)
        {
            mSideChaining.CurrentPosition = chainigPosition;
            mSideChaining.ProcessTime(sound_left, sound_left_out);
            mSideChaining.ProcessTime(sound_right, sound_right_out);
        }

        public void Setup(double volume, double fallback, double curve, double distance, int samplesPerBeat)
        {
            SetVolyme(volume);
            SetFallbackCurve(curve);
            SetFallbackDistance(distance, samplesPerBeat);
            SetFallback(fallback, samplesPerBeat);
        }
    }
}
